import { Label, _decorator, Node } from 'cc';
;

import { BattleCountdownStart, cat, Room, RoomEvent, RoomStatus, UILayer } from '../../../Test';

const { ccclass, property } = _decorator;

type StartTimeTickProps = {

}
type StartTimeTickData = {

}

@ccclass('GameTimeTick')
export class GameTimeTick extends UILayer<StartTimeTickProps, StartTimeTickData> {

    @property(Label)
    timeLable: Label


    @property(Node)
    time_node: Node

    override data: StartTimeTickData = {

    }

    protected override initUI(): void {

    }



    protected override onAutoObserver(): void {

        this.addAutorun([
            () => {
                this.time_node.active = RoomStatus.READIED === cat.store.room.roomInfo.status
            }
        ])

    }

    protected override onEventListener(): void {
        cat.event.on<RoomEvent>(RoomEvent.RoomBattleCountdownStart, this.onRoomBattleCountdownStartHandler, this)
    }

    private onRoomBattleCountdownStartHandler(data: BattleCountdownStart) {
        this.unscheduleAllCallbacks()

        const { countdownTime, serviceTime } = data
        const diff = Number(serviceTime) - Date.now()
        const cb = () => {
            const now = Date.now() + diff // 估算当前服务器时间
            const remainTime = ~~((Number(countdownTime) - now) / 1000)
            if (remainTime < 0) {
                this.onCloseHandler();
            } else {
                this.timeLable.string = `(${remainTime}s)`
            }
        }

        this.schedule(cb, 0.016)
    }

    private onCloseHandler() {
        this.unscheduleAllCallbacks()
    }


}


